<template>
  <div>
    <div class="formTitle">奖品设置</div>
    <el-table :data="tableData" border stripe>
      <el-table-column prop="name" label="奖品名称" width="180" />
      <el-table-column prop="amount" label="奖品数量" width="180" />
      <el-table-column prop="prizeResidue" label="剩余数量" />
      <el-table-column prop="level" label="奖品等级" />
      <el-table-column prop="probability" label="中获概率" />
      <el-table-column prop="type_id" label="奖品类型" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="warning" size="small" @click="changeList(scope.row)">
            修改
          </el-button>
          <el-button type="danger" size="small" @click="delList(scope.row.key)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button type="primary" class="addButton" @click="AddList(ruleFormRef)">
      添加
    </el-button>
    <!-- 弹框 -->
    <el-dialog v-model="dialogFormVisible" width="400px">
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-position="left"
        :rules="rules"
      >
        <el-form-item label="奖品名称" label-width="80px" prop="name">
          <el-input
            v-model="form.name"
            autocomplete="off"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="奖品数量" label-width="80px" prop="amount">
          <el-input
            v-model="form.amount"
            autocomplete="off"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="奖品等级" label-width="80px" prop="level">
          <el-input
            v-model="form.level"
            autocomplete="off"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="奖品类型" label-width="80px" prop="type_id">
          <el-select v-model="form.type_id" placeholder="">
            <el-option
              v-for="item in trophy"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="积分值"
          label-width="80px"
          prop="score"
          v-if="scoreShow"
        >
          <el-input
            v-model="form.score"
            autocomplete="off"
            style="width: 220px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outAdd(ruleFormRef)">Cancel</el-button>
          <el-button type="primary" @click="AddOver(ruleFormRef)">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeMount, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

 interface AddListRule {
    amount: string
    key: number
    level: string
    name: string
    prizeResidue: string
    probability: string
    score: string
    type_id: string
}

let tableData = ref<AddListRule[]>([
  {
    // 只能是key
    key: 1,
    name: "奖品1",
    amount: "20",
    prizeResidue: "20",
    level: "3",
    probability: "",
    type_id: "实物",
    score: "",
  },
  {
    key: 2,
    name: "奖品2",
    amount: "30",
    prizeResidue: "30",
    level: "2",
    probability: "",
    type_id: "券码",
    score: "",
  },
]);

let form = ref<AddListRule>({
  name: "",
  amount: "",
  prizeResidue: "",
  level: "",
  type_id: "",
  probability: "",
  score: "",
  key: 0,
});

const rules = reactive<FormRules>({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  amount: [
    {
      required: true,
      message: "Please input Activity amount",
      trigger: "blur",
    },
  ],
  level: [
    { required: true, message: "Please input Activity level", trigger: "blur" },
  ],
  type_id: [
    {
      required: true,
      message: "Please input Activity type_id",
      trigger: "change",
    },
  ],
  score: [
    { required: true, message: "Please input Activity score", trigger: "blur" },
  ],
});

const ruleFormRef = ref<FormInstance>();

const trophy = [
  { id: "1", name: "实物" },
  { id: "2", name: "积分" },
  { id: "3", name: "券码" },
];

const scoreShow = computed(() => {
  return form.value.type_id == "积分";
});

const dialogFormVisible = ref(false);


onBeforeMount(() => {
  changProbability(tableData.value);
});

const changProbability = (arr: AddListRule[]) => {
  let num = 0;
  arr.forEach((item) => (num += Number(item.amount)));
  tableData.value = arr.map((item) => {
    return {
      ...item,
      probability: (Number(item.amount) / num).toFixed(2),
    };
  });
};

const AddList = (formEl: FormInstance | undefined) => {
  //写在完成中会出现  赋值后马上清空的现象  但也没影响
  nextTick(() => {
    form.value = {
      name: "",
      amount: "",
      prizeResidue: "",
      level: "",
      type_id: "",
      probability: "",
      score: "",
      key: 0,
    };
    if (!formEl) return;
    formEl.resetFields();
  });

  dialogFormVisible.value = true;
};

const changeList = (item: AddListRule) => {
  form.value = { ...item };
  dialogFormVisible.value = true;
};

const delList = (key: number) => {
  tableData.value = tableData.value.filter((item) => item.key != key);
};

const outAdd = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
};

const AddOver = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (form.value.key) {
        // console.log("编辑");
        let arr = [...tableData.value];
        arr.splice(
          tableData.value.findIndex((item) => item.key == form.value.key),
          1,
          {
            ...form.value,
            prizeResidue: form.value.amount,
            score: scoreShow.value ? form.value.score : "",
          }
        );
        changProbability(arr);
      } else {
        // console.log("新增");
        let newTable = [
          ...tableData.value,
          {
            ...form.value,
            prizeResidue: form.value.amount,
            key: tableData.value.length + 1,
          },
        ];
        changProbability(newTable);
      }
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
    // formEl.resetFields();
  });
};
</script>

<style scoped >
.formTitle {
  font-size: 18px;
  margin-bottom: 10px;
}
.addButton {
  display: block;
  margin: auto;
  margin-top: 10px;
}
</style>
